import { cuesAttachmentPreview } from '@/services/api/api-cues-attachment';
import { adoptRecord, getCuesSubmitDetails } from '@/services/api/api-cues-submit';
import { DownloadOutlined } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
  Alert,
  Button,
  Descriptions,
  Divider,
  Image,
  message,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';

interface DetailsSubmitProps {
  id: string | undefined;
  name: string | undefined;
  onRefurbish: () => void;
  submitId: string;
}

const DetailsSubmit: React.FC<DetailsSubmitProps> = ({ id, name, onRefurbish, submitId }) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<CuesSubmitData.SubmitDetails>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  const handleLoad = () => {
    setPreviewLoading(false);
  };
  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);
  useEffect(() => {
    if (submitId === id) {
      if (submitId !== undefined) {
        setDrawerFormVisible(true);
      }
    }
  }, []);
  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await getCuesSubmitDetails({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={details?.articleName}
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: 900,
      }}
      trigger={<a>{name}</a>}
      onOpenChange={(visible) => {
        if (visible) {
          getSubmitDetails();
        } else {
          onRefurbish();
        }
        setDrawerFormVisible(visible);
      }}
      open={drawerFormVisible}
      submitter={{
        render: (props, dom) => {
          return [
            access.选题计划x收录 && details?.isAdopt === 0 && (
              <ModalForm
                title="是否收录"
                trigger={<Button type="primary">收录</Button>}
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  destroyOnClose: true,
                }}
                onFinish={async (values) => {
                  const response = await adoptRecord({ id, channel: 1 });
                  if (response.code === 0) {
                    message.success('收录成功！');
                    getSubmitDetails();
                    return true;
                  }
                }}
              >
                {name}
              </ModalForm>
            ),
          ];
        },
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        <Descriptions>
          <Descriptions.Item label="报送单位">{details?.articleOrganizationName}</Descriptions.Item>
          <Descriptions.Item label="报送人">{details?.articleAccountName}</Descriptions.Item>
          {/* <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item> */}
          <Descriptions.Item label="报送时间">{details?.createdTime}</Descriptions.Item>
        </Descriptions>
        {access.线索征集x配置x管理员 &&
          Array.isArray(details?.adoptOrganizationNames) &&
          details?.adoptOrganizationNames?.length > 0 && (
            <Descriptions>
              <Descriptions.Item label="收录单位">
                <Space size={[0, 8]} wrap>
                  {Array.isArray(details?.adoptOrganizationNames) &&
                    details?.adoptOrganizationNames?.map((item) => {
                      return <Tag key={item}>{item}</Tag>;
                    })}
                </Space>
              </Descriptions.Item>
            </Descriptions>
          )}
        <Descriptions>
          <Descriptions.Item label="选题方向">
            <Space size={[0, 8]} wrap>
              {details?.articleIndustrys?.map((item) => {
                return <Tag key={item.value}>{item.label}</Tag>;
              })}
            </Space>
          </Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="标签">
            {details?.articleLabels.map((item) => {
              return <Tag key={item.value}>{item.label}</Tag>;
            })}
          </Descriptions.Item>
        </Descriptions>
        {details?.articleSetDate && (
          <Descriptions column={3}>
            <Descriptions.Item label="线索日期">{details?.articleSetDate}</Descriptions.Item>
          </Descriptions>
        )}
        {details?.articleLocation && (
          <Descriptions column={3}>
            <Descriptions.Item label="地点">{details?.articleLocation}</Descriptions.Item>
          </Descriptions>
        )}
        {details?.articleHighlight && (
          <Descriptions column={3}>
            <Descriptions.Item label="亮点">{details?.articleHighlight}</Descriptions.Item>
          </Descriptions>
        )}
        {details?.contacts && (
          <Descriptions>
            <Descriptions.Item span={3} label="联络方式">
              <Space size={[8, 16]} wrap>
                {details?.contacts &&
                  details?.contacts.map((item) => (
                    <span style={{ marginRight: 5 }}>
                      <a>{item.name}</a> - <a>{item.phone}</a>
                    </span>
                  ))}
              </Space>
            </Descriptions.Item>
          </Descriptions>
        )}
        <Divider />
        {details?.articleName ? (
          <Typography.Title level={3} style={{ textAlign: 'center' }}>
            {details?.articleName}
          </Typography.Title>
        ) : (
          <></>
        )}
        <br />
        {details?.articleContent ? (
          <div
            dangerouslySetInnerHTML={{
              __html: `${details?.articleContent}`,
            }}
          />
        ) : (
          <></>
        )}
        {details?.articleAttachments && details?.articleAttachments.length > 0 && (
          <>
            <Divider />
            <div
              style={{
                textAlign: 'right',
              }}
            >
              <Button
                type="primary"
                key="import"
                size="small"
                icon={<DownloadOutlined />}
                onClick={() => {
                  details?.articleAttachments.forEach(function (item) {
                    window.open(item.content, '_blank');
                  });
                }}
              >
                全部下载
              </Button>
            </div>

            <Upload
              listType="picture"
              multiple
              fileList={details?.articleAttachments.map((item) => {
                return {
                  uid: item.id,
                  name: item.name,
                  url: item.content,
                  mimeType: item.mimeType,
                  status: 'done',
                };
              })}
              showUploadList={{
                downloadIcon: (
                  <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                    <DownloadOutlined
                      style={{
                        marginRight: '10px',
                      }}
                    />
                    点击下载
                  </div>
                ),
                showRemoveIcon: false,
                showDownloadIcon: true,
              }}
              onPreview={async (file: UploadFile) => {
                setPreviewData({
                  id: file.uid,
                  name: file.name,
                  mimeType: file.mimeType,
                  url: encodeURI(file.url),
                });
                setPreviewOpen(true);
              }}
            />
            <DrawerForm
              title={previewData?.name}
              drawerProps={{
                width: 900,
                destroyOnClose: true,
              }}
              open={previewOpen}
              onOpenChange={async (visible) => {
                if (visible) {
                  if (
                    previewData?.mimeType !== null &&
                    previewData?.mimeType?.indexOf('image') > -1
                  ) {
                    //图片预览
                  } else {
                    setPreviewLoading(true);

                    const response = await cuesAttachmentPreview({
                      id: previewData?.id,
                    });

                    if (response.code === 0) {
                      setPreviewOnlineUrl(response.data);
                    } else {
                      message.error('暂时无法预览');
                      setPreviewLoading(false);
                    }
                  }
                } else {
                  setPreviewOpen(false);
                  setPreviewData(undefined);
                  setPreviewOnlineUrl(undefined);
                }
              }}
              submitter={{
                searchConfig: {
                  submitText: '下载',
                },
              }}
              onFinish={async (values) => {
                window.open(previewData?.url, '_blank');
              }}
            >
              <Alert
                style={{
                  marginBottom: 20,
                }}
                message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                type="warning"
                showIcon
              />
              {previewData?.mimeType !== null && previewData?.mimeType?.indexOf('image') > -1 ? (
                <Image width="100%" src={previewData?.url} />
              ) : (
                <Spin spinning={previewLoading}>
                  <iframe
                    ref={iframeRef}
                    src={previewOnlineUrl}
                    height={windowSize.innerHeight - 220}
                    width="100%"
                    frameBorder="0"
                    // scrolling="false"
                    allowFullScreen={true}
                    // scrolling={'no'}
                  />
                </Spin>
              )}
            </DrawerForm>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsSubmit;
